package com.keeping.aiimagery.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.keeping.aiimagery.Config.LocalCache;
import com.keeping.aiimagery.handler.strategy.MessageStrategy;
import com.keeping.aiimagery.listener.OpenAIWebSocketEventSourceListener;
import com.keeping.aiimagery.util.StrUtils;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.ChatCompletion;
import com.unfbx.chatgpt.entity.chat.Message;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息策略
 */
@Component
public class ChatMsgStrategy implements MessageStrategy {

    private static OpenAiStreamClient openAiStreamClient;

    @Autowired
    public void setOrderService(OpenAiStreamClient openAiStreamClient) {
        this.openAiStreamClient = openAiStreamClient;
    }

    public ChatMsgStrategy() {
    }


    @SneakyThrows
    @Override
    public void sendText(Session session, String userId, String roomId, String msg) {
        //接受参数
        OpenAIWebSocketEventSourceListener eventSourceListener = new OpenAIWebSocketEventSourceListener(session, userId,
                roomId);
        String messageContext = (String) LocalCache.CACHE.get(StrUtils.getWebSocketKey(userId, roomId));
        List<Message> messages = new ArrayList<>();
        if (StrUtil.isNotBlank(messageContext)) {
            messages = JSONUtil.toList(messageContext, Message.class);
            if (messages.size() >= 10) {
                messages = messages.subList(1, 10);
            }
            Message currentMessage = Message.builder().content(msg).role(Message.Role.USER).build();
            messages.add(currentMessage);
        } else {
            Message currentMessage = Message.builder().content(msg).role(Message.Role.USER).build();
            messages.add(currentMessage);
        }
        ChatCompletion chatCompletion = ChatCompletion.builder().messages(messages).stream(true).build();
        openAiStreamClient.streamChatCompletion(chatCompletion,eventSourceListener);
        LocalCache.CACHE.put(StrUtils.getWebSocketKey(userId, roomId), JSONUtil.toJsonStr(messages), LocalCache.TIMEOUT);
    }
}
